const path = require('path')
const fs = require('fs')
const electron = require('electron')

class Store {
    constructor() {
        // 获取用户数据目录
        const userDataPath = (electron.app || electron.remote.app).getPath('userData')
        this.path = path.join(userDataPath, 'settings.json')
        
        // 默认设置
        this.defaults = {
            noteSettings: {
                width: 300,
                height: 400,
                fontSize: 14
            }
        }

        this.data = this.loadData()
        
        // 确保初始化时有默认值
        if (!this.data.noteSettings) {
            this.data.noteSettings = this.defaults.noteSettings
            this.save()
        }
    }

    // 加载数据
    loadData() {
        try {
            return fs.existsSync(this.path) 
                ? JSON.parse(fs.readFileSync(this.path, 'utf8'))
                : this.defaults
        } catch (error) {
            console.error('加载设置失败:', error)
            return this.defaults
        }
    }

    // 获取设置
    get(key) {
        return this.data[key] || this.defaults[key]
    }

    // 保存设置
    set(key, value) {
        this.data[key] = value
        return this.save()
    }

    // 保存到文件
    save() {
        try {
            fs.writeFileSync(this.path, JSON.stringify(this.data, null, 2))
            return true
        } catch (error) {
            console.error('保存设置失败:', error)
            return false
        }
    }

    // 验证设置值是否在有效范围内
    validateSettings(settings) {
        const validated = {
            width: Math.min(Math.max(settings.width || this.defaults.noteSettings.width, 200), 800),
            height: Math.min(Math.max(settings.height || this.defaults.noteSettings.height, 200), 800),
            fontSize: Math.min(Math.max(settings.fontSize || this.defaults.noteSettings.fontSize, 12), 24)
        }
        return validated
    }
}

module.exports = Store 